let timer = null;
const ball = document.querySelector(".ball");
let disX = 2;
let disY = 2;

const w = document.documentElement.clientWidth;
const h = document.documentElement.clientHeight;
const ew = ball.clientWidth;
const eh = ball.clientHeight;
let maxLeft = w - ew;
let maxTop = h - eh;

function getRandom(min, max) {
  return Math.floor(Math.random() * (max - min) + min);
}

function changeBg() {
  ball.style.background = `rgb(${getRandom(0, 256)}, ${getRandom(
    0,
    256
  )}, ${getRandom(0, 256)})`;
}

timer = setInterval(function () {
  const rect = ball.getBoundingClientRect();
  const x = rect.left;
  const y = rect.top;
  let left = x + disX;
  let top = y + disY;

  if (left > maxLeft) {
    left = maxLeft;
    disX = -disX;
    changeBg();
  }

  if (left < 0) {
    left = 0;
    disX = -disX;
    changeBg();
  }

  if (top > maxTop) {
    top = maxTop;
    disY = -disY;
    changeBg();
  }

  if (top < 0) {
    top = 0;
    disY = -disY;
    changeBg();
  }

  ball.style.left = left + "px";
  ball.style.top = top + "px";
}, 20);
